"""
---------------------------------------------------------------------
- File: common.py
- Date: 2025/8/9
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 项目相关复用依赖
---------------------------------------------------------------------
"""

import jwt
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from jwt import InvalidTokenError

# schemas
from app.api.v1.endpoints.security.schemas import UserOut
from app.common.app_utils import snake_case_convert

# models
from app.models.system_manage.user import User

from app.core.config import app_settings, SECRET_KEY, ALGORITHM

tokenUrl = f"/api/{app_settings.APP_VERSION}/security/token"
oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl=tokenUrl, scheme_name="OAuth2PasswordBearer"
)


async def get_current_user(request: Request, token: str = Depends(oauth2_scheme)):
    """获取当前请求的用户信息"""
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无效的认证，请重新登录",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        # payload.userNo是经过 Pydantic 命名转换过，操作之前先转回来
        payload = UserOut(**snake_case_convert(payload))
        user = await User.get_or_none(user_no=payload.user_no, status=True)
        if not user:
            raise credentials_exception

        # 将信息保存到请求中，方便后续使用
        request.state.current_user = user
        return payload
    except InvalidTokenError:
        raise credentials_exception
    except Exception:
        raise credentials_exception
